package com.spica.spicaschool.di

import android.content.Context
import coil.ImageLoader
import coil.request.Disposable
import coil.request.ImageRequest
import coil.transform.CircleCropTransformation
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ActivityComponent
import dagger.hilt.android.qualifiers.ActivityContext
import dagger.hilt.android.scopes.ActivityScoped
import io.noties.markwon.Markwon
import io.noties.markwon.html.HtmlPlugin
import io.noties.markwon.image.AsyncDrawable
import io.noties.markwon.image.coil.CoilImagesPlugin

/**
 * 注入Markdown转译工具
 */
@InstallIn(ActivityComponent::class)
@Module
object MarkwonModule {


    @Provides
    @ActivityScoped
    fun provideMarkwon(
        @ActivityContext appContext: Context,
        coilImagesPlugin: CoilImagesPlugin
    ): Markwon {
        return Markwon
            .builder(appContext)
            .usePlugin(coilImagesPlugin)
            .usePlugin(HtmlPlugin.create())
            .build()
    }


    /**
     * 图片加载器
     */
    @Provides
     fun provideColiImagesPlugin(@ActivityContext context: Context): CoilImagesPlugin {
        val imageLoader = ImageLoader.Builder(context)
            .apply {
                availableMemoryPercentage(0.5)
                bitmapPoolPercentage(0.5)
                crossfade(true)
            }
            .build()

        return CoilImagesPlugin.create(
            object : CoilImagesPlugin.CoilStore {
                override fun load(drawable: AsyncDrawable): ImageRequest {
                    return ImageRequest.Builder(context)
                        .defaults(imageLoader.defaults)
                        .data(drawable.destination)
                        .crossfade(true)
                        .build()
                }

                override fun cancel(disposable: Disposable) {
                    disposable.dispose()
                }
            },
            imageLoader
        )
    }


}